package Algorithm.LinkedListProblem;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author cj
 * @Date 2022/1/5 20:27
 */
public class removeRep {

    static class Node {
        public int value;
        public Node next;

        public Node(int val) {
            this.value = val;
        }
    }

    public static Node removeRep1(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        Set<Integer> set = new HashSet<>();
        Node cur = head.next, pre = head;
        set.add(head.value);
        while (cur != null) {
            if (set.contains(cur.value)) {
                // 执行删除操作
                pre.next = cur.next;
            } else {
                set.add(cur.value);
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }

    // 类似选择排序
    public static Node removeRep2(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        Node cur = head, move = null, pre = null;
        while (cur != null) {
            pre = cur;
            move = cur.next;
            while (move != null) {
                if (move.value == cur.value) {
                    // 删除
                    pre.next = move.next;
                } else {
                    pre = move;
                }
                move = move.next;
            }
            cur = cur.next;
        }
        return head;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(4);
        head.next.next.next.next.next = new Node(4);
        head.next.next.next.next.next.next = new Node(2);
        head.next.next.next.next.next.next.next = new Node(1);
        head.next.next.next.next.next.next.next.next = new Node(1);
        Node a = removeRep2(head);
        while (a != null) {
            System.out.println(a.value);
            a = a.next;
        }
    }

}
